/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.sys.controller;

import com.chengcang.admin.common.annotation.LogOperation;
import com.chengcang.admin.common.utils.ExcelUtils;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.security.user.UserDetail;
import com.chengcang.admin.modules.sys.dto.PasswordDTO;
import com.chengcang.admin.modules.sys.dto.PasswordResetDTO;
import com.chengcang.admin.modules.sys.dto.SysUserDTO;
import com.chengcang.admin.modules.sys.dto.SysUserUpdateDTO;
import com.chengcang.admin.modules.sys.excel.SysUserExcel;
import com.chengcang.admin.modules.sys.service.SysDeptService;
import com.chengcang.admin.modules.sys.service.SysRoleService;
import com.chengcang.admin.modules.sys.service.SysUserService;
import com.chengcang.common.constant.Constant;
import com.chengcang.common.exception.CustomException;
import com.chengcang.common.exception.ErrorCode;
import com.chengcang.common.page.PageData;
import com.chengcang.common.utils.ConvertUtils;
import com.chengcang.common.utils.PasswordUtils;
import com.chengcang.common.utils.Result;
import com.chengcang.common.validator.AssertUtils;
import com.chengcang.common.validator.ValidatorUtils;
import com.chengcang.common.validator.group.AddGroup;
import com.chengcang.common.validator.group.DefaultGroup;
import com.chengcang.common.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 用户管理
 *
 * @author zhanli
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
@RequiredArgsConstructor
public class SysUserController {
    private final SysUserService sysUserService;
    private final SysDeptService sysDeptService;
    private final SysRoleService sysRoleService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "username", value = "ID/手机号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态 0 启用 1 禁用", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "source", value = "注册渠道", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query"),
            @ApiImplicitParam(name = "tenantId", value = "客户ID", paramType = "query"),
            @ApiImplicitParam(name = "deptId", value = "部门ID", paramType = "query"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "query"),
    })
    @RequiresPermissions("sys:user:page")
    public Result<PageData<SysUserDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysUserDTO> page = sysUserService.page(params);

        return new Result<PageData<SysUserDTO>>().ok(page);
    }

    @GetMapping("rolePage")
    @ApiOperation("按角色分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "tenantId", value = "客户ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "roleId", value = "角色ID", paramType = "query"),
    })
    @RequiresPermissions("sys:user:rolePage")
    public Result<PageData<SysUserDTO>> rolePage(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysUserDTO> page = sysUserService.rolePage(params);

        return new Result<PageData<SysUserDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sys:user:info")
    public Result<SysUserDTO> get(@PathVariable("id") Long id) {
        SysUserDTO data = sysUserService.get(id);

        return new Result<SysUserDTO>().ok(data);
    }

    @GetMapping("list")
    @ApiOperation("用户列表")
    @RequiresPermissions("sys:user:list")
    public Result<List<SysUserDTO>> list() {
        List<SysUserDTO> data = sysUserService.list(new HashMap<>(1));

        return new Result<List<SysUserDTO>>().ok(data);
    }

    @GetMapping("info")
    @ApiOperation("登录用户信息")
    public Result<SysUserDTO> info() {
        SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class);
        Optional.ofNullable(data).ifPresent(oo->{
            Optional.ofNullable(data.getDeptId()).ifPresent(o ->
                    data.setDeptName(sysDeptService.get(data.getDeptId()).getName()));
            Optional.ofNullable(data.getRoleId()).ifPresent(o ->
                    data.setRoleName(sysRoleService.get(data.getRoleId()).getName()));
        });
        return new Result<SysUserDTO>().ok(data);
    }

    @PutMapping("password")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public Result password(@RequestBody PasswordDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto);

        UserDetail user = SecurityUser.getUser();

        //原密码不正确
        if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) {
            return new Result().error(ErrorCode.PASSWORD_ERROR);
        }

        sysUserService.updatePassword(user.getId(), dto.getNewPassword());

        return new Result();
    }

    @PutMapping("reset")
    @ApiOperation("重置默认密码")
    @LogOperation("重置默认密码")
    public Result reset(@RequestBody PasswordResetDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto);

        sysUserService.resetPassword(dto.getUserId(), dto.getRemark());

        return new Result();
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sys:user:save")
    public Result save(@RequestBody SysUserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysUserService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
//	@RequiresPermissions("sys:user:update")
    public Result update(@RequestBody SysUserDTO dto) {

        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        // 放开权限，验证是否拥有修改的权限(当前修改userId是否属于登录用户的客户)
        if (SecurityUser.getTenantId() != null) {
            SysUserDTO sysUserDTO = sysUserService.get(dto.getId());
            if (sysUserDTO.getTenantList().stream().noneMatch(item -> item.getTenantId().equals(SecurityUser.getTenantId()))) {
                throw new CustomException("当前用户不允许修改此数据！");
            }
        }

        sysUserService.update(dto);

        return new Result();
    }

    @PutMapping("batch")
    @ApiOperation("批量修改部门和角色")
    @LogOperation("批量修改部门和角色")
    @RequiresPermissions("sys:user:updateBatch")
    public Result update(@RequestBody SysUserUpdateDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysUserService.updateBatch(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sys:user:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        sysUserService.deleteBatchIds(Arrays.asList(ids));

        return new Result();
    }

    @GetMapping("delete")
    @ApiOperation("禁用启用")
    @LogOperation("禁用启用")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "ids", value = "用户id"),
            @ApiImplicitParam(required = true, name = "status", value = "0 正常 1 禁用"),
            @ApiImplicitParam(required = false, name = "remark", value = "备注")
    })
    @RequiresPermissions("sys:user:status")
    public Result forbid(@RequestParam Long[] ids, @RequestParam Integer status,
                         @RequestParam(required = false) String remark) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        sysUserService.forbidTenant(ids, status, remark);
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sys:user:export")
    @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SysUserDTO> list = sysUserService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, list, SysUserExcel.class);
    }
}
